package cn.yuanqiao.archive.tongji.service.impl;

import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.SysSyConfigMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.service.ISysSyConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.appManager.service.ITenantSysDictTypeService;
import cn.yuanqiao.archive.liyong.domain.TenantDownloadRecord;
import cn.yuanqiao.archive.liyong.domain.YqDy;
import cn.yuanqiao.archive.liyong.domain.YqMyCollect;
import cn.yuanqiao.archive.tongji.mapper.TongJiMapper;
import cn.yuanqiao.archive.tongji.service.TongJiService;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtilTJ;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.time.Year;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author zjj
 * @date 2023/7/28
 */
@Service
public class TongJiServiceImpl implements TongJiService {
    @Autowired
    private TongJiMapper tongJiMapper;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private ITenantSysDictTypeService dictTypeService;
    @Autowired
    private SysSyConfigMapper sysSyConfigMapper;

    @Autowired
    private RemoteActivitiService remoteActivitiService;
    @Autowired
    private ISysSyConfigService sysSyConfigService;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Value("${archiveLogPath}")
    private String logPath;


    @Override
    public JSONArray menlei(String startTime, String endTime) {
        String tenantCode = SecurityUtils.getTenantCode();
        //门类统计数据
        List<Map<String,Object>> resList = tongJiMapper.menlei(startTime,endTime,tenantCode);
        TenantCategory select = new TenantCategory();
        //获取使用的门类 门类里有件表就说明这个门类在用
        List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryListIsUse(select);
        int[] zong = {0,0,0,0};
        JSONArray array = new JSONArray();
        for(TenantCategory category:categoryList){
            JSONObject parMljson = new JSONObject();
            parMljson.put("name",category.getName());
            Integer type = category.getType();
            if(type == 3 || type == 1){
                String juan = getNum(resList,category.getFolderTableName(),"3");
                zong[0] += Integer.valueOf(juan);
                parMljson.put("juanNum",juan);

                String juanneijian = getNum(resList,category.getFileTableName(),"1");
                zong[1] += Integer.valueOf(juanneijian);
                parMljson.put("juanneijian",juanneijian);

                String juanjianYs = getNum(resList,category.getFileTableName(),"2");
                zong[3] += Integer.valueOf(juanjianYs);
                parMljson.put("docNum",juanjianYs);

                parMljson.put("jianNum","-");
            }else if(type == 0){
                parMljson.put("juanNum","-");
                parMljson.put("juanneijian","-");

                String juanneijian = getNum(resList,category.getFileTableName(),"1");
                zong[2] += Integer.valueOf(juanneijian);
                parMljson.put("jianNum",juanneijian);

                String jianYs = getNum(resList,category.getFileTableName(),"2");
                zong[3] += Integer.valueOf(jianYs);
                parMljson.put("docNum",jianYs);
            }
            array.add(parMljson);
        }
        JSONObject xiaoji = new JSONObject();
        xiaoji.put("name","小计");
        //xiaoji.put("rowspan","0");
        //xiaoji.put("childName","");
        xiaoji.put("juanNum",zong[0]);
        xiaoji.put("juanneijian",zong[1]);
        xiaoji.put("jianNum",zong[2]);
        xiaoji.put("docNum",zong[3]);
        array.add(xiaoji);

        return array;
    }

    @Override
    public JSONObject kucun(String startTime, String endTime, Long deptId) {
        List<TenantSysDictData> dictData = dictTypeService.selectDictDataByType("BGQX");
        List<Long> depts = null;
        if(deptId!=null){
            depts = tongJiMapper.getDeptListByPraentId(deptId);
        }
        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String,Object>> dataList = tongJiMapper.kucun(dictData,startTime,endTime,depts,tenantCode);
        for (Map<String, Object> map : dataList) {
            Set<String> keys = new HashSet<>(map.keySet()); // 避免在循环中修改集合
            for (String key : keys) {
                if (key.contains("BGQX_")) {
                    Object value = map.get(key);
                    map.remove(key); // 先移除原来的键值对
                    String newKey = key.replace("BGQX_", ""); // 替换特定字符
                    map.put(newKey, value); // 添加新的键值对
                }
            }
        }
        JSONObject object = new JSONObject();
        object.put("data",dataList);
        object.put("dictData",dictData);
        return object;
    }

    @Override
    public JSONArray ysmenlei() {
        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String,Object>> dataList = tongJiMapper.ysmenlei(tenantCode);
        JSONArray array = new JSONArray();
        for(int i=0;i<dataList.size();i++) {
            String name=String.valueOf(dataList.get(i).get("NAME"));
            if(StringUtils.isEmpty(name)){
                name="未知门类";
            }
            JSONObject object = new JSONObject();
            object.put("value",dataList.get(i).get("COUNT"));
            object.put("name",name);
            array.add(object);
        }
        return array;
    }

    @Override
    public JSONArray ysfwl() {
        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String,Object>> dataList = tongJiMapper.ysfwl(tenantCode);
        JSONArray array = new JSONArray();
        for(int i=0;i<dataList.size();i++) {
            JSONObject object = new JSONObject();
            object.put("value",dataList.get(i).get("COUNT"));
            object.put("name",dataList.get(i).get("NAME"));
            array.add(object);
        }
        return array;
    }

    @Override
    public JSONArray wdjy() {
        String tenantCode = SecurityUtils.getTenantCode();
        Long userId = SecurityUtils.getUserId();
        Map<String,Object> dataList = tongJiMapper.wdjy(userId,tenantCode);
        JSONArray array = new JSONArray();
        JSONObject YIHUAN = new JSONObject();
        YIHUAN.put("value",dataList.get("YIHUAN"));
        YIHUAN.put("name","已逾期");
        array.add(YIHUAN);
        JSONObject WEIHUAN = new JSONObject();
        WEIHUAN.put("value",dataList.get("WEIHUAN"));
        WEIHUAN.put("name","未还");
        array.add(WEIHUAN);
        JSONObject SHENPIZHONG = new JSONObject();
        SHENPIZHONG.put("value",dataList.get("SHENPIZHONG"));
        SHENPIZHONG.put("name","申请中");
        array.add(SHENPIZHONG);
        return array;
    }

    @Override
    public JSONObject sygdqk() {
        JSONArray array = new JSONArray();
        array.add("product");
        String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        for(int j=3;j>=0;j--) {
            array.add(Integer.parseInt(year)-j);
        }

        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String,Object>> typelist = tongJiMapper.getYqdaSubtable(tenantCode);
        JSONArray data = new JSONArray();
        for (int i = 0; i < typelist.size(); i++) {
            StringBuffer sb = new StringBuffer();
            sb.append("SELECT * FROM ");
            for (int j = 3; j >= 0; j--) {
                sb.append("(SELECT count(1) AS \"" + (Integer.parseInt(year) - j)
                        + "\" FROM "+tenantCode+"_yqda WHERE state=5 AND SUB_TABLE_NAME='" + typelist.get(i).get("SUB_TABLE_NAME")
                        + "' AND create_time >='" + (Integer.parseInt(year) - j)
                        + "-01-01 00:00:00' AND create_time <='" + (Integer.parseInt(year) - j) + "-12-31 23:59:59'),");
            }
            sb = sb.deleteCharAt(sb.length() - 1);
            List<Map<String, Object>> yeartypelist = tongJiMapper.getListResult(sb.toString());
            JSONObject object = new JSONObject();
            object.put("product",typelist.get(i).get("NAME"));
            object.put(String.valueOf((Integer.parseInt(year) - 3)),yeartypelist.get(0).get(String.valueOf(Integer.parseInt(year) - 3)));
            object.put(String.valueOf((Integer.parseInt(year) - 2)),yeartypelist.get(0).get(String.valueOf(Integer.parseInt(year) - 2)));
            object.put(String.valueOf((Integer.parseInt(year) - 1)),yeartypelist.get(0).get(String.valueOf(Integer.parseInt(year) - 1)));
            object.put(year,yeartypelist.get(0).get(year));
            data.add(object);
        }
        JSONObject res = new JSONObject();
        res.put("data", data);
        res.put("years", array);
        return res;
    }

    @Override
    public JSONArray symrjyl() {
        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String,Object>> dataList = tongJiMapper.symrjyl(tenantCode);
        JSONArray array = new JSONArray();
        for(int i=0;i<dataList.size();i++) {
            JSONObject object = new JSONObject();
            object.put("value",dataList.get(i).get("COUNT"));
            object.put("name",dataList.get(i).get("NAME"));
            array.add(object);
        }
        return array;
    }

    @Override
    public JSONObject syInfo() {
        String tenantCode = SecurityUtils.getTenantCode();
        Long userId = SecurityUtils.getUserId();
        String userName = SecurityUtils.getUsername();
        JSONObject object = new JSONObject();
        //获取最后登陆日期
        String accessTime = tongJiMapper.topAccessTime(userName,tenantCode);
        object.put("lastTime",accessTime);
        //今天登陆次数
        Integer count = tongJiMapper.tadayCount(userName,tenantCode);
        object.put("tadayCount",count == null ? 0:count);
        //首页展示内容
        Boolean bl = SecurityUtils.isDagly();
        List<SysRole> roleList = SecurityUtils.getLoginUser().getUser().getRoles();
        StringBuilder roles = new StringBuilder();
        if(roleList!=null && roleList.size()>0){
            for(SysRole role:roleList){
                roles.append("'").append(role.getRoleKey()).append("',");
            }
            roles.deleteCharAt(roles.length()-1);
            String roleName = roles.toString();
            List<String> list = sysSyConfigMapper.selectSysSyConfigDistinct(roleName,1,tenantCode);
            JSONArray jsonArray = sysSyConfigService.getSyConfigName();
            object.put("zsInfo",list);
            List<String> kjlist = sysSyConfigMapper.selectSysSyConfigDistinct(roleName,2,tenantCode);
            JSONArray kjarray = new JSONArray();
            for(String name:kjlist){
                for(int i = 0;i<jsonArray.size();i++){
                    if(name.equals(jsonArray.getJSONObject(i).getString("value"))){
                        kjarray.add(jsonArray.getJSONObject(i));
                        break;
                    }
                }
            }
            object.put("kjInfo",kjarray);
            List<String> dblist = sysSyConfigMapper.selectSysSyConfigDistinct(roleName,3,tenantCode);
            JSONArray dbarray = new JSONArray();
            for(String name:dblist){
                dbarray.add(name);
            }
            object.put("dbInfo",dbarray);

            List<String> grzx = sysSyConfigMapper.selectSysSyConfigDistinct(roleName,4,tenantCode);
            JSONArray grzxarray = new JSONArray();
            for(String name:grzx){
                grzxarray.add(name);
            }
            object.put("grzx",grzxarray);
        }



        //object.put("roleName",roleName);
        //借阅数量 待归还（state=1加上state=3）、借阅中（state=1）、已逾期（state=3）件数量
        JSONObject dbCount = new JSONObject();
        //待审核
        R<List<Map<String, Object>>> processCount = remoteActivitiService.getTaskSummaryForUser();
        List<Map<String, Object>> data = processCount.getData();
        Integer daishenhe = new Integer(0);
        for (Map<String, Object> item : data) {
            Integer dsh = (Integer) item.get("待办");
            daishenhe += dsh;
        }
        dbCount.put("dshCount",daishenhe);
        //申请中
        Integer dghCount = tongJiMapper.getBorrowCountByState((bl ? null:userId),("'4'"),tenantCode);
        dbCount.put("dghCount",dghCount == null ? 0:dghCount);
        //借阅中
        Integer jyzCount = tongJiMapper.getBorrowCountByState((bl ? null:userId),("'0'"),tenantCode);
        dbCount.put("jyzCount",jyzCount == null ? 0:jyzCount);
        //已逾期
        Integer yyqCount = tongJiMapper.getBorrowCountByState((bl ? null:userId),("'3'"),tenantCode);
        dbCount.put("yyqCount",yyqCount == null ? 0:yyqCount);
        //待组卷   中铁 过程文件门类在离线接收
        String categoryId = sysConfigService.selectConfigByKey("ztUpdateStateTask.categoryId");
        Integer dzjCount = 0;
        if(StringUtils.isNotEmpty(categoryId)){
            dzjCount = tongJiMapper.getDzjCount(new DataScopeBase(22923L),categoryId,tenantCode);
        }
        dbCount.put("dzjCount",dzjCount);

        //我的订阅
        int wddyCount = tongJiMapper.getwddyCount(new YqDy().getTableName(),userId);
        dbCount.put("wddyCount",wddyCount);
        //我的下载
        Integer wdxzCount = tongJiMapper.getwdxzCount(new TenantDownloadRecord().getTableName(),userId);
        dbCount.put("wdxzCount",wdxzCount == null ? 0:wdxzCount);
        //我的收藏
        int wdscCount = tongJiMapper.getwdscCount(new YqMyCollect().getTableName(),userId);
        dbCount.put("wdscCount",wdscCount);

        object.put("dbCount",dbCount);

        return object;
    }

    private String getNum(List<Map<String,Object>> resList,String tabName,String type){
        String num = "0";
        for(Map<String,Object> ml:resList){
            if(tabName.equals(ml.get("SUB_TABLE_NAME")) && type.equals(String.valueOf(ml.get("TYPE")))){
                num = (ml.get("NUM") == null ? "0":String.valueOf(ml.get("NUM")));
                break;
            }
        }
        return num;
    }

    @Override
    public JSONArray lytj(String startTime,String endTime) {
        String tenantCode = SecurityUtils.getTenantCode();
        if(StringUtils.isNotEmpty(endTime)){
            endTime = endTime + " 23:59:59";
        }
        List<Map<String,Object>> dataList = tongJiMapper.lytj(startTime,endTime,tenantCode);
        JSONArray array = new JSONArray();
        for(int i=0;i<dataList.size();i++) {
            JSONObject object = new JSONObject();
            object.put("value",dataList.get(i).get("COUNT"));
            object.put("name",dataList.get(i).get("NAME"));
            object.put("downloadCount",(dataList.get(i).get("DOWNLOAD_COUNT") == null ? 0:dataList.get(i).get("DOWNLOAD_COUNT")));
            object.put("ys",(dataList.get(i).get("YS") == null ? 0:dataList.get(i).get("YS")));
            array.add(object);
        }
        return array;
    }

    @Override
    public JSONArray sjlytj(String startTime, String endTime, String ids) {
        List<TenantCategory> categoryList = null;
        StringBuilder xmSubTableName = new StringBuilder();
        StringBuilder juanSubTableName = new StringBuilder();
        StringBuilder jianSubTableName = new StringBuilder();
        if(StringUtils.isNotEmpty(ids)){
            categoryList = categoryMapper.getCategoryById(ids,new TenantCategory().getTableName());
            for(TenantCategory category:categoryList){
                xmSubTableName.append("'").append(category.getItemTableName()).append("',");
                juanSubTableName.append("'").append(category.getFolderTableName()).append("',");
                jianSubTableName.append("'").append(category.getFileTableName()).append("',");
            }
            if(xmSubTableName.length()>0){
                xmSubTableName.deleteCharAt(xmSubTableName.length()-1);
            }
            if(juanSubTableName.length()>0){
                juanSubTableName.deleteCharAt(juanSubTableName.length()-1);
            }
            if(jianSubTableName.length()>0){
                jianSubTableName.deleteCharAt(jianSubTableName.length()-1);
            }
        }else {
            categoryList = categoryMapper.selectTenantCategoryListIsUse(new TenantCategory());
        }
        //项目层
        List<Map<String,Object>> xmList = tongJiMapper.sjlytj(new TenantYqItem().getTableName(),(xmSubTableName.length()>0 ? xmSubTableName.toString():null),startTime,endTime);
        //卷层
        List<Map<String,Object>> juanList = tongJiMapper.sjlytj(new TenantYqFolder().getTableName(),(juanSubTableName.length()>0 ? juanSubTableName.toString():null),startTime,endTime);
        //件层
        List<Map<String,Object>> jianList = tongJiMapper.sjlytj(new TenantYqda().getTableName(),(jianSubTableName.length()>0 ? jianSubTableName.toString():null),startTime,endTime);

        JSONArray array = new JSONArray();
        for(TenantCategory category:categoryList){
            JSONObject object = new JSONObject();
            object.put("name",category.getName());
            //处理项目
            object.put("xm-lx","0");
            object.put("xm-zx","0");
            object.put("xm-da","0");
            if(category.getType() == 3){
                for (Map<String,Object> xm:xmList){
                    if(category.getItemTableName().equals(xm.get("SUB_TABLE_NAME"))){
                        if("0".equals(xm.get("JS_TYPE"))){
                            object.put("xm-lx",xm.get("NUM"));
                        }else if("1".equals(xm.get("JS_TYPE"))){
                            object.put("xm-zx",xm.get("NUM"));
                        }else if("2".equals(xm.get("JS_TYPE"))){
                            object.put("xm-da",xm.get("NUM"));
                        }
                    }
                }
            }
            //处理卷
            object.put("juan-lx","0");
            object.put("juan-zx","0");
            object.put("juan-da","0");
            if(category.getType()==1){
                for (Map<String,Object> xm:juanList){
                    if(category.getFolderTableName().equals(xm.get("SUB_TABLE_NAME"))){
                        if("0".equals(xm.get("JS_TYPE"))){
                            object.put("juan-lx",xm.get("NUM"));
                        }else if("1".equals(xm.get("JS_TYPE"))){
                            object.put("juan-zx",xm.get("NUM"));
                        }else if("2".equals(xm.get("JS_TYPE"))){
                            object.put("juan-da",xm.get("NUM"));
                        }
                    }
                }
            }
            //处理件
            object.put("jian-lx","0");
            object.put("jian-zx","0");
            object.put("jian-da","0");
            for (Map<String,Object> xm:jianList){
                if(category.getFileTableName().equals(xm.get("SUB_TABLE_NAME"))){
                    if("0".equals(xm.get("JS_TYPE"))){
                        object.put("jian-lx",xm.get("NUM"));
                    }else if("1".equals(xm.get("JS_TYPE"))){
                        object.put("jian-zx",xm.get("NUM"));
                    }else if("2".equals(xm.get("JS_TYPE"))){
                        object.put("jian-da",xm.get("NUM"));
                    }
                }
            }
            //电子文件
            object.put("file-lx","0");
            object.put("file-zx","0");
            object.put("file-da","0");
            List<Map<String,Object>> eFileList = tongJiMapper.sjlytjEFile(category.getEfileTableName(),category.getFileTableName(),startTime,endTime);
            for (Map<String,Object> xm:eFileList){
                if("0".equals(xm.get("JS_TYPE"))){
                    object.put("file-lx",xm.get("NUM"));
                }else if("1".equals(xm.get("JS_TYPE"))){
                    object.put("file-zx",xm.get("NUM"));
                }else if("2".equals(xm.get("JS_TYPE"))){
                    object.put("file-da",xm.get("NUM"));
                }
            }
            array.add(object);
        }
        return array;
    }

    @Override
    public List<Map> fwltj(String startTime, String endTime) {
        List<String> date = null;
        String format = "";
        if(StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)){
            //统计当前月的每一天
            date = DateUtilTJ.getDaysBetween(DateUtilTJ.firstDayOfMonth(), DateUtilTJ.nowDay());
            format = "YYYY-MM-DD";
        }else {
            //先判断日期是否在同一年
            if(DateUtilTJ.isSameYear(startTime,endTime)){
                if(DateUtilTJ.isSameMonth(startTime,endTime)){
                    //以天为统计单位
                    date = DateUtilTJ.getDaysBetween(startTime,endTime);
                    format = "YYYY-MM-DD";
                }else {
                    //以月为统计单位
                    date = DateUtilTJ.getMonthsBetween(startTime,endTime);
                    format = "YYYY-MM";
                }
            }else {
                //以年为统计单位
                date = DateUtilTJ.getYearsBetween(startTime,endTime);
                format = "YYYY";
            }
        }
        List<Map> list = tongJiMapper.fwltj(String.join(",",date),format,SecurityUtils.getTenantCode());
        return list;
    }

    @Override
    public Map<String,Integer> storageSpaceTj() {
        File logsFile = new File(logPath);
        if(logsFile.exists()){
            //获取磁盘总大小
            long totalSpace = logsFile.getTotalSpace();
            //获取磁盘可用空间大小
            long freeSpace = logsFile.getFreeSpace();

            int total = (int) (totalSpace/1024/1024);
            int free = (int) (freeSpace/1024/1024);
            int used = total - free;

            Map<String,Integer> file = new HashMap<>();
            file.put("total",total);
            file.put("free",free);
            file.put("used",used);
            return file;
        }else {
            throw new ServiceException("存储空间路径配置错误,路径不存在!");
        }
    }
    /**
     * 格式统计
     * @return
     */
    @Override
    public Map<String, Object> gstj(String startTime, String endTime) {
        TenantCategory select = new TenantCategory();
        List<String> docType = new ArrayList<>();
        List<Map<String, Object>> sumList = new ArrayList<>();
        com.alibaba.fastjson.JSONArray returnList = new com.alibaba.fastjson.JSONArray();
        com.alibaba.fastjson.JSONArray returnList2 = new com.alibaba.fastjson.JSONArray();
        //获取使用的门类 门类里有件表就说明这个门类在用
        List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryListIsUse(select);
        List<Map<String, Object>> fondsList = tongJiMapper.getFondsList(SecurityUtils.getTenantCode());
        com.alibaba.fastjson.JSONArray returnListFonds2 = new com.alibaba.fastjson.JSONArray();
        for (Map<String, Object> fonds:fondsList){
            List<TenantCategory> categoryListFonds = categoryList.stream().filter(f -> fonds.get("FONDS_CODE").equals(f.getFondsCode())).collect(Collectors.toList());
            com.alibaba.fastjson.JSONArray returnListFonds = new com.alibaba.fastjson.JSONArray();
            for (TenantCategory category : categoryListFonds) {
                com.alibaba.fastjson.JSONObject tjmap = new com.alibaba.fastjson.JSONObject();
                List<Map<String, Object>> maps = tongJiMapper.getgstjDocType(category.getEfileTableName(),
                        SecurityUtils.getTenantCode(),category.getFileTableName(),startTime,endTime);
                tjmap.put("categoryName", category.getName());
                tjmap.put("categoryId", category.getId());
                tjmap.put("tj", maps);
                tjmap.put("DOCSUM", maps.stream().collect(Collectors.summingInt(c->Integer.parseInt(String.valueOf(c.get("SUMTYPE"))))));
                returnListFonds.add(tjmap);
                returnListFonds2.add(tjmap);
                docType.addAll(maps.stream().map(f -> f.get("DOC_FILE_TYPE").toString()).collect(Collectors.toList()));
                sumList.addAll(maps);
            }
            com.alibaba.fastjson.JSONObject returnMapFonds = new com.alibaba.fastjson.JSONObject();
            returnMapFonds.put("fondsName",fonds.get("FONDS_NAME"));
            returnMapFonds.put("categoryList",returnListFonds);
            returnList.add(returnMapFonds);
        }
        com.alibaba.fastjson.JSONObject returnMapFonds = new com.alibaba.fastjson.JSONObject();
        returnMapFonds.put("categoryList",returnListFonds2);
        returnList2.add(returnMapFonds);
        Map<Object, Integer> collect = sumList.stream().collect(Collectors.groupingBy(c -> c.get("DOC_FILE_TYPE"),
                Collectors.summingInt(c->Integer.parseInt(c.get("SUMTYPE").toString()))));
        com.alibaba.fastjson.JSONObject map = new com.alibaba.fastjson.JSONObject();
        map.put("heji", collect);
        Stream<String> distinct = docType.stream().distinct();
        List<String> collect1 = distinct.collect(Collectors.toList());
        map.put("type",collect1);
        map.put("gslist1", returnList);
        //前端默认获取第一组数据展示，暂无用全宗分类展示 20250328
        map.put("gslist", returnList2);
        return map;
    }

    /**
     * 年度统计
     * @return
     */
    @Override
    public Map<String, Object> ndtj(String startTime, String endTime) {
        TenantCategory select = new TenantCategory();
        List<Integer> docType = new ArrayList<>();
        List<Map<String, Object>> sumList = new ArrayList<>();
        com.alibaba.fastjson.JSONArray returnList = new com.alibaba.fastjson.JSONArray();
        if(org.apache.commons.lang3.StringUtils.isEmpty(startTime)){
            int value = Year.now().getValue();
            endTime =String.valueOf(value);
            startTime = String.valueOf(value-4);
        }
        int  i= Integer.parseInt(endTime) - Integer.parseInt(startTime);
        while (i>=0){
            docType.add((Integer.parseInt(startTime)+i));
            i--;
        }
        //获取使用的门类 门类里有件表就说明这个门类在用
        List<TenantCategory> categoryList = categoryMapper.selectTenantCategoryListIsUse(select);
        List<Map<String, Object>> fondsList = tongJiMapper.getFondsList(SecurityUtils.getTenantCode());
        for (Map<String, Object> fonds:fondsList){
            List<TenantCategory> categoryListFonds = categoryList.stream().filter(f -> fonds.get("FONDS_CODE").equals(f.getFondsCode())).collect(Collectors.toList());
            com.alibaba.fastjson.JSONArray returnListFonds = new com.alibaba.fastjson.JSONArray();
            for (TenantCategory category : categoryListFonds) {
                String subtablename = "'"+category.getFileTableName()+"'";
                if (category.getType()!=0){
                    subtablename =subtablename+",'"+category.getFolderTableName()+"'";
                }
                List<Map<String, Object>> maps = tongJiMapper.getNdType(SecurityUtils.getTenantCode(),startTime,endTime,subtablename);
                com.alibaba.fastjson.JSONObject tjmap = new com.alibaba.fastjson.JSONObject();
                tjmap.put("categoryName", category.getName());
                tjmap.put("categoryId", category.getId());
                List<Object> nd1 = maps.stream().map(m -> String.valueOf(m.get("ND"))).collect(Collectors.toList());
                List<Integer> nd = docType.stream().filter(f -> !nd1.contains(String.valueOf(f))).collect(Collectors.toList());
                if (nd!=null&&nd.size()>0){
                    for (Integer  n: nd) {
                        Map<String, Object>  mm = new HashMap<>();
                        mm.put("FOLDERSUM",0);
                        mm.put("FIELSUM",0);
                        mm.put("ND",String.valueOf(n));
                        maps.add(mm);
                    }
                }
                tjmap.put("tj", maps);
                returnListFonds.add(tjmap);
                sumList.addAll(maps);
            }
            com.alibaba.fastjson.JSONObject returnMapFonds = new com.alibaba.fastjson.JSONObject();
            returnMapFonds.put("fondsName",fonds.get("FONDS_NAME"));
            returnMapFonds.put("categoryList",returnListFonds);
            returnList.add(returnMapFonds);
        }
        com.alibaba.fastjson.JSONObject map = new com.alibaba.fastjson.JSONObject();
        map.put("type", docType.stream().distinct().collect(Collectors.toList()));
        map.put("ndList", returnList);
        return map;
    }

    /**
     * 全宗统计
     * @return
     */
    @Override
    public com.alibaba.fastjson.JSONArray qztj(String startTime, String endTime) {
        com.alibaba.fastjson.JSONArray returnList = new com.alibaba.fastjson.JSONArray();
        List<Map<String, Object>> fondsList = tongJiMapper.getQzType(SecurityUtils.getTenantCode(),startTime,endTime);
        Integer filesum = fondsList.stream().collect(Collectors.summingInt(c -> Integer.parseInt(c.get("FILESUM").toString())));
        Integer foldersum = fondsList.stream().collect(Collectors.summingInt(c -> Integer.parseInt(c.get("FOLDERSUM").toString())));
        com.alibaba.fastjson.JSONObject collect = new com.alibaba.fastjson.JSONObject();
        collect.put("FILESUM",filesum);
        collect.put("FOLDERSUM",foldersum);
        com.alibaba.fastjson.JSONObject map = new com.alibaba.fastjson.JSONObject();
        map.put("heji", collect);
        map.put("qzlist", fondsList);
        returnList.add(map);
        return returnList;
    }

    /**
     * 档案馆全宗统计
     * @return
     */
    @Override
    public com.alibaba.fastjson.JSONArray dagqztj(String startTime, String endTime) {
        com.alibaba.fastjson.JSONArray returnList = new com.alibaba.fastjson.JSONArray();
        List<Map<String, Object>> fondsList = tongJiMapper.getDagQzType(SecurityUtils.getTenantCode(),startTime,endTime);
        Integer filesum = fondsList.stream().collect(Collectors.summingInt(c -> Integer.parseInt(c.get("FILESUM").toString())));
        Integer foldersum = fondsList.stream().collect(Collectors.summingInt(c -> Integer.parseInt(c.get("FOLDERSUM").toString())));
        com.alibaba.fastjson.JSONObject collect = new com.alibaba.fastjson.JSONObject();
        collect.put("FILESUM",filesum);
        collect.put("FOLDERSUM",foldersum);
        com.alibaba.fastjson.JSONObject map = new com.alibaba.fastjson.JSONObject();
        map.put("heji", collect);
        map.put("qzlist", fondsList);
        returnList.add(map);
        return returnList;
    }

    /**
     * 利用满意度统计
     * @return
     */
    @Override
    public com.alibaba.fastjson.JSONArray lymydtj (String startTime, String endTime) {
        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String,Object>> dataList = tongJiMapper.getlymyd(tenantCode,startTime,endTime);
        com.alibaba.fastjson.JSONArray array = new com.alibaba.fastjson.JSONArray();
        for(int i=0;i<dataList.size();i++) {
            com.alibaba.fastjson.JSONObject object = new com.alibaba.fastjson.JSONObject();
            object.put("name",dataList.get(i).get("CSAT").equals("1")?"一般":dataList.get(i).get("CSAT").equals("2")?"满意":"十分满意");
            object.put("value",dataList.get(i).get("CSATNUM")==null?0:Long.valueOf(String.valueOf(dataList.get(i).get("CSATNUM"))));
            array.add(object);
        }
        return array;
    }


}
